#include "stdint.h"
#include "stdio.h"
#include "sdkconfig.h"
#include "cpuusage.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "freertos/timers.h"

#include "parameters.h"

#include "DevicesDelay.h"
#include "DevicesADC.h"
#include "DevicesKey.h"
#include "DevicesLed.h"
#include "DevicesQueue.h"
#include "DevicesSPI.h"
#include "DevicesSPIFlash.h"
#include "DevicesTimer.h"
#include "DevicesUart.h"
#include "DevicesSoftTimer.h"
#include "DevicesTime.h"
#include "DevicesPWM.h"
#include "DevicesWatchDog.h"

#include "gatts_table.h"
#include "station.h"
#include "udp_server.h"
#include "tcp_server.h"
#include "mqtt.h"

#include "taskKey.h"
#include "taskSoftTimer.h"
#include "taskNetwork.h"
#include "taskSystem.h"


TaskHandle_t g_TaskSystemInitHand = NULL;  /* 系统初始化任务句柄 */


void vApplicationIdleHook( void )
{
    vCPUUsageIdleHook();

    vWatchdogReload();
}

void vUserSystemInit(void)
{
    vParametersInit();

    enumQueueInit();

    vPWM0Init();

    vLedInit();

    vKeyInit();

    vUart1Init();

    cSoftTimerInit();

    printf("ble_init Free memory: %d bytes\r\n", (int)esp_get_free_heap_size());
    ble_init();
    printf("ble_init Free memory: %d bytes\r\n", (int)esp_get_free_heap_size());

    printf("wifi_init Free memory: %d bytes\r\n", (int)esp_get_free_heap_size());
    wifi_init();
    printf("wifi_init Free memory: %d bytes\r\n", (int)esp_get_free_heap_size());

    udp_server_init();

    printf("mqtt_init Free memory: %d bytes\r\n", (int)esp_get_free_heap_size());
    mqtt_init();
    printf("mqtt_init Free memory: %d bytes\r\n", (int)esp_get_free_heap_size());

//    vWatchdogInit();
}

void vTaskSystemInit(void *pvParameters)
{
    printf("FreeRTOS start succeed...\r\n");


    xTaskCreate(vTaskKey,                "Key",          2048,    NULL, configMAX_PRIORITIES - 2, &g_TaskKeyHand);

    xTaskCreate(vTaskNetwork,            "Network",      4096,    NULL, configMAX_PRIORITIES - 3, &g_TaskNetworkHand);


    vUserSystemInit();

    printf("SystemInit succeed.\r\n");

    /* 删除自己 */
    vTaskDelete( NULL );
}
